// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

var util = require('../../utils/util');
var common = require('../../utils/userstatus');
var app = getApp();
Component({
  data: {
    shareId: "",
    chatList: [],
    defaultUserStatus: common.userStatus[0].value,
    scrollViewHeight: "",
    nvabarData: {
      // homeCapsule: false,
      // title: '车上说',
      // fontColor: "black",
      // fontSize: '26rpx',
      // headerbg: '#f5f5f5',
      // hiddenBlock: false,
      // slot: false
    },
    navHeight: app.globalData.navHeight + app.globalData.statusHeight,
    navHeightHidden: app.globalData.navHeightHidden
  },
  methods: {
    onLoad() {
      const token = wx.getStorageSync('accessToken');
      if (!token) {
        wx.redirectTo({
          url: '/pages/login/login'
        })
        return;
      }
      const addUserId = wx.getStorageSync('sharedId');
      console.log("addUserId:" + addUserId)
      if (addUserId) {
        wx.removeStorageSync('sharedId');
        const storeId = wx.getStorageSync('userInfo').id;
        if (storeId && addUserId == storeId) {
          this.getChatList();
          wx.showToast({
            title: '不能添加自己',
            icon: 'error',
            duration: 2000
          })
          return;
        }
        console.log("添加好友----")
        wx.showLoading({
          title: '添加好友中...',
        })
        util.postRequest("/applet/addFriend", {
          userId: storeId,
          friendId: addUserId
        }, (data) => {
          console.log(data)
          wx.hideLoading();
          this.getChatList();
          if (data.code == 2000) {
            wx.showToast({
              title: '添加成功',
              icon: 'error',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: data.message,
              icon: 'error',
              duration: 2000
            })
          }
        }, (error) => {
          this.getChatList();
          wx.hideLoading();
          wx.showToast({
            title: '添加失败',
            icon: 'error',
            duration: 2000
          })
        })
      } else {
        this.getChatList();
      }
      this.setData({
        search: this.search.bind(this)
      })
      this.refreshToken();
      this.getUserStatusList();
      //主页开启分享
      wx.showShareMenu({
        withShareTicket: true
      })
    },
    addPerson() {
      var code = util.getRandomCode(10);
      this.data.shareId = code;
      console.log("随机数" + this.data.shareId)
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage'],
        complete: () => {
          console.log("分享成功")
          this.getShareUid();
        }
      })

    },
    onShareAppMessage() {
      var id = wx.getStorageSync('userInfo').id;
      var code = this.data.shareId;
      var path = '/pages/share/share?id=' + id +
        '&code=' + code;
      console.log(path)
      return {
        title: "分享添加好友",
        path: path,
        imageUrl: '../../images/index/youkongma.jpg'
      }
    },
    getShareUid() {
      var url = '/applet/getShareUid';

      var id = wx.getStorageSync('userInfo').id;
      var data = {
        id: id,
        code: this.data.shareId
      }
      if (this.data.shareId) {
        util.postRequest(url, data)
      }
    },

    getScrollHeight() {
      var query = wx.createSelectorQuery();
      query.select('#mp-searchbar').boundingClientRect()
      query.exec((res) => {
        console.log(res)
        if (res) {
          if (!res[0] || res[0] === null) {
            return;
          }
          var height = res[0].height;
          if (height) {
            wx.getSystemInfo({
              success: (res) => {
                this.setData({
                  scrollViewHeight: res.windowHeight - res.statusBarHeight - height - 48
                })
              },
              fail: function (res) {},
              complete: function (res) {},
            })
          }
        }
      })
    },
    // 用户事件捕获
    markPhoneCatch() {
      return false;
    },
    markPhone(e) {
      var index = e.currentTarget.dataset.index;
      var info = this.data.chatList[index];
      var phoneNumber = info.phoneNumber;
      if (phoneNumber) {
        wx.makePhoneCall({
          phoneNumber: phoneNumber + "",
          fail: (error) => {
            wx.showToast({
              title: error.errno,
              icon: 'error',
              duration: 2000
            })
          }
        })
      } else {
        wx.showToast({
          title: '无可用手机号',
          icon: 'error',
          duration: 2000
        })
      }
    },
    onPullDownRefresh() {
      this.getChatList();
      this.getUserStatusList();
      wx.stopPullDownRefresh();
    },
    getUserStatusList() {
      var url = "/applet/static/getResource";
      util.postRequest(url, {

      }, (data) => {
        if (data.code === 2000) {
          if (data.list && data.list.length > 0) {
            data.list.forEach(item => {
              item.path = util.backServerUrl + item.path
            })
            wx.setStorageSync('userStatusList', data.list)
          }
        }
      }, (error) => {

      });
    },
    refreshToken() {
      var globalData = getApp().globalData;
      console.log(globalData.interval)
      if (globalData.interval) {
        try {
          globalData.interval.clearInterval();
          globalData.interval = "";
        } catch (e) {
          console.log(e)
        }
      }
      globalData.interval = setInterval(() => {
          // 刷新token
          const today = new Date();
          var day = this.formatDate(today)
          console.log(day)
          var intervalDay = wx.getStorageSync('intervalDay');
          if (intervalDay === day) {
            console.log("--已处理--")
            return
          }
          console.log("--refresh--")
          var url = "/applet/refreshToken";
          util.postRequest(
            url, {
              id: wx.getStorageSync('userInfo').id,
              refreshToken: wx.getStorageSync('refreshToken')
            },
            (data) => {
              if (data.code == 2000) {
                wx.setStorageSync('refreshToken', data.data.refreshToken)
                wx.setStorageSync('accessToken', data.data.accessToken)
                wx.setStorageSync('intervalDay', day)
              }
            },
            (error) => {

            });

        },
        3 * 60 * 1000
      )

    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return year + month + day;
    },
    search(value) {
      if (!this.data.chatList ||
        (this.data.chatList && this.data.chatList.length == 0)) {
        return;
      }
      return new Promise((resolve, reject) => {
        var newData = [];
        for (var index = 0; index < this.data.chatList.length; index++) {
          var item = this.data.chatList[index];
          if (item.username.includes(value)) {
            newData.push({
              value: index,
              text: item.username
            })
          }
        }
        resolve(newData)
      })
    },
    getChatList() {
      util.postRequest("/applet/selectFriendList", {
        id: wx.getStorageSync('userInfo').id
      }, (data) => {
        wx.hideLoading();
        if (data.code == 2000) {
          data.list.forEach(item => {
            if (item.userStatusStr === 'null' || !item.userStatusStr) {
              item.userStatusStr = common.userStatus[0].value;
            }
            if (item.profileImagePath &&
              !item.profileImagePath.includes("http")) {
              item.profileImagePath = util.backServerUrl + item.profileImagePath;
            }
          })
          wx.setStorageSync('chatList', data.list)
          this.setData({
            chatList: data.list
          })
          this.getScrollHeight();
        } else {
          this.setData({
            chatList: wx.getStorageSync('chatList')
          })
        }
      }, (error) => {
        this.setData({
          chatList: wx.getStorageSync('chatList')
        })
      })
    },
    bindinputFuc(e) {
      console.log(e)
    },
    bindselectresult(e) {
      console.log(e)
      var index = e.detail.item.value;
      var obj = {
        currentTarget: {
          dataset: {
            index: index
          }
        }
      };
      this.openContent(obj)
    },
    openContent(e) {
      var index = e.currentTarget.dataset.index;
      var info = this.data.chatList[index];
      console.log(index)
      console.log(info)
      wx.navigateTo({
        url: '/pages/otherinfo/otherinfo',
        events: {
          backShow: (data) => {
            this.setData({
              chatList: wx.getStorageSync('chatList')
            })
          },
          getListAgain: (data) => {
            this.getChatList();
          }
        },
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          // 如果为false 表示不能修改
          res.eventChannel.emit('infoData', {
            data: info,
            index: index
          })
        }
      })

    },
    bindViewTap() {},
    onInputChange(e) {
      const nickName = e.detail.value
      const {
        avatarUrl
      } = this.data.userInfo
      this.setData({
        "userInfo.nickName": nickName,
        hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      })
    }
  },
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 0
        })
      }
    }
  }
})